<!DOCTYPE html>
<html lang="ch-CN">
<head>
    <meta charset="UTF-8">
    <title>鼠标实时位置</title>
</head>
<style>
    body {
        margin: 0;
        padding: 0;
        width: 100%;
        height: 100vh;
        background-color: wheat;
        font-size: 30px;
        /*文本透明*/
        /*text-decoration: none;*/
        font-family: "华文楷体";
        display: flex;
        flex-direction: column;
        /*justify-content: center;*/
        align-items: center;
    }

    p {
        font-size: 40px;
        margin: 20px 0 0 0;
        font-weight: bold;
    }

    span {
        /*display: block;*/
        line-height: 50px;
    }

    #box1 {
        width: 500px;
        height: 300px;
        background-color: #b3b1af;
        border: solid 1px black;
        position: relative;
    }
#box1>div{
    width: 100px;
    height: 100px;
    background-color: white;
    border: solid black 1px;
}

    #box2 {
        margin-top: 50px;
        width: 500px;
        background-color: khaki;
        border: solid 1px black;
        text-align: center;
    }

</style>
<body id="body">
<div id="box1">
    <div id="box1_son"></div>
</div>
<div id="box2">
    <p>指针离盒子的位置</p>
</div>
</body>
<script>
    let box1 = document.getElementById("box1")
    let box2 = document.getElementById("box2")
    let body = document.getElementById("body")
    let box1_son = document.getElementById("box1_son")
    // 添加两个p元素到box2中用来查看当前指针对于box1的位置
    let index_X = document.createElement("p")
    let index_Y = document.createElement("p")
    index_X.style.margin = "0"
    index_Y.style.margin = "0"
    index_X.style.fontWeight = "none"
    index_Y.style.fontWeight = "none"
    index_X.style.fontSize = "30px"
    index_Y.style.fontSize = "30px"
    box2.appendChild(index_X)
    box2.appendChild(index_Y)
    // 添加一个div到box1跟随指针指向的位置
    let son = document.createElement("div")
    // son.style.display="none"
    son.style.width = "30px"
    son.style.height = "30px"
    son.style.backgroundColor = "black";
    box1.appendChild(son)

    box1.onmousemove = function (event) {
        // 用于适配火狐浏览器或者 event=event||window.event
        if (!event) {
            event = window.event
        }
        // 查看当前指针对于box1的位置
        index_X.innerHTML = "离盒子左侧距离：" + event.offsetX
        index_Y.innerHTML = "离盒子顶部距离：" + event.offsetY
        // son.style.display="block"
        // son.style.position="relative"
        // son.style.top=event.offsetY+"px"
        // son.style.left=event.offsetX+"px"
        // 方法二：
        // son.style.marginTop=event.offsetY+"px"
        // son.style.marginLeft=event.offsetX+"px"
        son.style.marginTop=(event.offsetY)-(box1_son.scrollHeight)+"px"
        son.style.marginLeft=event.offsetX+"px"
        // 方法三：
        // son.style.transform = `translate(${event.offsetX}px, ${event.offsetY}px)`
    }
</script>
</html>